package com.example.login.service.impl;

import com.example.login.config.AliyunSmsConfig;
import com.example.login.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private List<AliyunSmsConfig.SmsConfig> smsConfigs;
    
    @Value("${sms.expiration}")
    private int codeExpiration;
    
    @Value("${sms.length}")
    private int codeLength;
    
    // 短信验证码Redis前缀
    private static final String SMS_CODE_PREFIX = "sms:code:";
    
    @Override
    public boolean sendVerificationCode(String phone) {
        try {
            String code = generateVerificationCode(codeLength);
            
            redisTemplate.opsForValue().set(SMS_CODE_PREFIX + phone, code, codeExpiration, TimeUnit.SECONDS);
            
            log.info("模拟发送短信验证码：手机号 = {}, 验证码 = {}", phone, code);
            
            Map<String, String> templateParams = new HashMap<>();
            templateParams.put("code", code);
            
            AliyunSmsConfig.SmsConfig smsConfig = smsConfigs.get(0);
            log.info("使用阿里云短信配置：accessKey = {}, 签名 = {}, 模板CODE = {}", 
                    smsConfig.getAccessKeyId(), smsConfig.getSignName(), smsConfig.getTemplateCode());
            log.info("短信模板内容：您正在申请手机注册，验证码为：{}，5分钟内有效！", code);
            
            return true;
        } catch (Exception e) {
            log.error("发送短信验证码失败：", e);
            return false;
        }
    }
    
    private String generateVerificationCode(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
    
    @Override
    public boolean verifyCode(String phone, String code) {
        String key = SMS_CODE_PREFIX + phone;
        Object savedCode = redisTemplate.opsForValue().get(key);
        
        if (savedCode != null && savedCode.toString().equals(code)) {
            // 验证成功，不删除验证码，等待自然过期
            return true;
        }
        return false;
    }
}